import { Button, Drawer, Form, Input, InputNumber, Radio, TreeSelect, message } from "antd";
import { useEffect, useState } from "react";

import menuService from "@/api/services/system/menuService";
import type { Menu } from "#/entity";
import { BasicStatus, MenuType } from "#/enum";

export type MenuModalProps = {
	formValue: Menu;
	title: string;
	show: boolean;
	onOk: VoidFunction;
	onCancel: VoidFunction;
};

export default function MenuModal({ title, show, formValue, onOk, onCancel }: MenuModalProps) {
	const [form] = Form.useForm();
	const [menus, setMenus] = useState<Menu[]>([]);

	useEffect(() => {
		getMenus();
	}, []);

	const getMenus = async () => {
		try {
			const res = await menuService.queryAll();
			setMenus(res);
		} catch (error) {
			console.error("获取菜单列表失败:", error);
			message.error("获取菜单列表失败:");
		}
	};

	useEffect(() => {
		if (show) {
			if (formValue.parentId && formValue.parentId === "0") {
				formValue.parentId = undefined;
			}
			form.setFieldsValue({ ...formValue });
		}
	}, [show, formValue, form]);

	const handleSubmit = async (values: any) => {
		const finalValues = { ...formValue, ...values };
		try {
			console.log("保存菜单", finalValues);
			await menuService.saveOrUpdate(finalValues);
			message.success("保存成功");
			onOk();
			form.resetFields();
		} catch (error) {
			message.error(`${error.message}`);
		}
	};

	return (
		<Drawer
			title={title}
			open={show}
			onClose={onCancel}
			width={480}
			footer={
				<div className="flex justify-end gap-2">
					<Button onClick={onCancel}>取消</Button>
					<Button type="primary" onClick={() => form.submit()}>
						确定
					</Button>
				</div>
			}
		>
			<Form
				initialValues={formValue}
				form={form}
				onFinish={handleSubmit}
				labelCol={{ span: 6 }}
				wrapperCol={{ span: 18 }}
				layout="horizontal"
			>
				<Form.Item<Menu> label="类型" name="type" required>
					<Radio.Group optionType="button" buttonStyle="solid">
						<Radio value={MenuType.CATALOGUE}>目录</Radio>
						<Radio value={MenuType.MENU}>菜单</Radio>
						<Radio value={MenuType.BUTTON}>按钮</Radio>
					</Radio.Group>
				</Form.Item>

				<Form.Item<Menu> label="名称" name="name" required>
					<Input />
				</Form.Item>

				<Form.Item<Menu> label="父节点" name="parentId">
					<TreeSelect
						fieldNames={{
							label: "name",
							value: "id",
							children: "children",
						}}
						allowClear
						treeData={menus}
					/>
				</Form.Item>

				{formValue.type !== MenuType.BUTTON && (
					<Form.Item<Menu> label="路由" name="route" required>
						<Input />
					</Form.Item>
				)}
				<Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}>
					{({ getFieldValue }) => {
						if (getFieldValue("type") === MenuType.MENU) {
							return (
								<Form.Item<Menu> label="组件路径" name="component" required={getFieldValue("type") === MenuType.MENU}>
									<Input />
								</Form.Item>
							);
						}
						return null;
					}}
				</Form.Item>
				<Form.Item<Menu> label="权限标识" name="permission" tooltip="权限标识">
					<Input />
				</Form.Item>

				{formValue.type !== MenuType.BUTTON && (
					<Form.Item<Menu> label="图标" name="icon" tooltip="local icon should start with ic">
						<Input />
					</Form.Item>
				)}
				<Form.Item<Menu> label="是否隐藏" name="hidden" tooltip="隐藏菜单" required>
					<Radio.Group optionType="button" buttonStyle="solid">
						<Radio value={"0"}>显示</Radio>
						<Radio value={"1"}>隐藏</Radio>
					</Radio.Group>
				</Form.Item>

				<Form.Item<Menu> label="序号" name="sn">
					<InputNumber style={{ width: "100%" }} />
				</Form.Item>

				<Form.Item<Menu> label="状态" name="status" required>
					<Radio.Group optionType="button" buttonStyle="solid">
						<Radio value={BasicStatus.ENABLE}> 有效 </Radio>
						<Radio value={BasicStatus.DISABLE}> 失效 </Radio>
					</Radio.Group>
				</Form.Item>
			</Form>
		</Drawer>
	);
}
